from flask import  Flask, render_template,request,jsonify,escape
from PIL import Image
import requests
import matplotlib.pyplot as plt
import json

app = Flask(__name__)

def log_request(req: 'flask_request', res: str):
    with open('detect.log','a') as log:
        print(req.form,req.host_url,req.remote_addr,file=log,sep="|")

@app.route('/')
def hello() -> str:
 return "忘记输入/XXX啦 笨蛋"

@app.route("/login",methods=['get'])
def index()-> 'html':
    title ='欢迎来到ozl的名人识别网页'
    return render_template("login.html",the_title=title)

@app.route('/entry',methods=['post','get'])
def entry_page():
    url = request.form.get("person")
    log_request(request,url)
    return render_template('entry.html',the_title ="欢迎来识别人像!")

@app.route("/person",methods=["POST"])
def person():
    image_url=request.form["person"]
    subscription_key ="f50f8dee95c44dc49e378cc44b777644"
    assert subscription_key
    vision_base_url = "https://computer-vision-ozl.cognitiveservices.azure.com/vision/v3.1/"
    celebrity_analyze_url = vision_base_url + "models/celebrities/analyze"
    headers = {'Ocp-Apim-Subscription-Key': subscription_key}
    params = {'model': 'celebrities'}
    data = {'url': image_url}
    response = requests.post(
        celebrity_analyze_url, headers=headers, params=params, json=data)
    response.raise_for_status()
    analysis = response.json()
    celebrity_name = analysis["result"]["celebrities"][0]["name"].capitalize()
    confidence2=analysis["result"]["celebrities"][0]["confidence"]
    return render_template('entry.html',person=str(celebrity_name),confidence2=str(confidence2))

@app.route('/viewlog')
def view_log() -> 'html':
    contents=[]
    with open("detect.log","r") as log:
        for line in log:
            contents.append([])
            for item in line.split("|"):
                contents[-1].append(escape(item))
    titles= ["Formdata","Host_url","Remote_addr"]
    return render_template('view.html',the_data=contents,the_titles=titles)

if __name__ == '__main__':
 app.run(debug = True)